package com.example.xbrother.convertor;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.DataFormatData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;

import java.math.BigDecimal;

/**
 * 货币转换器
 */
public class CustomMoneyConverter implements Converter<BigDecimal> {
    @Override
    public Class<?> supportJavaTypeKey() {
        return BigDecimal.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * 这里是读的时候会调用 不用管
     *
     * @return
     */
    @Override
    public BigDecimal convertToJavaData(ReadConverterContext<?> context) {
        return context.getReadCellData().getNumberValue();
    }

    /**
     * 这里是写的时候会调用 不用管
     *
     * @return
     */
    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<BigDecimal> context) {
        WriteCellData<?> writeCellData = new WriteCellData<>(context.getValue());
        WriteCellStyle writeCellStyle = new WriteCellStyle();
        DataFormatData dataFormatData = new DataFormatData();
        // 设置货币格式，并保留2位小数
        dataFormatData.setFormat("¥#,##0.00_);[Red](¥#,##0.00)");
        writeCellStyle.setDataFormatData(dataFormatData);
        writeCellData.setWriteCellStyle(writeCellStyle);
        return writeCellData;
    }

}